package com.zhuoyue.biz.core.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.zhuoyue.biz.core.api.appjson.EzviewMessageBean;
import com.zhuoyue.biz.core.api.dao.SysThirdDataMapper;
import com.zhuoyue.biz.core.api.domain.third.EzViewDO;
import com.zhuoyue.biz.core.api.dto.EzResult;
import com.zhuoyue.biz.core.api.dto.rep.EzvizTokenRepDTO;
import com.zhuoyue.common.api.XmlParse;
import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import com.zhuoyue.common.utils.EzviewPost;
import com.zhuoyue.common.xml.XmlParseUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;

import com.zhuoyue.biz.core.api.dao.EzvizTokenDao;
import com.zhuoyue.biz.core.api.domain.EzvizTokenDO;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wjming
 * @ClassName: EzvizTokenService
 * @Description:萤石摄像头Toke业务操作
 * @Date 2021-06-24 20:34
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class EzvizTokenService extends ServiceImpl<EzvizTokenDao, EzvizTokenDO> {
    private final RedisTemplate redisTemplate;
    private final SysThirdDataMapper thirdDataMapper;
    RestTemplate restTemplate = new RestTemplate();


    public EzvizTokenRepDTO getEzvizTokenByHomeId(EzvizTokenDO et) {
        EzvizTokenDO ezvizTokenDO = getOne(Wrappers.<EzvizTokenDO>lambdaQuery().eq(EzvizTokenDO::getHomeId, et.getHomeId()));
        if (ezvizTokenDO == null) {
            throw new ZyServerException(ErrorType.result_not_exist);
        }
        EzvizTokenRepDTO ezvizTokenRepDTO = new EzvizTokenRepDTO().ezvizTokenDoToEzvizTokenRepDto(ezvizTokenDO);
        return ezvizTokenRepDTO;
    }

    /**
     * 查询萤石摄像头
     *
     * @param homeId
     * @return
     */
    public Integer removeRemoteEz(String homeId, String organizationCode) {
        List<EzvizTokenDO> integer = list(Wrappers.<EzvizTokenDO>lambdaQuery().eq(EzvizTokenDO::getHomeId, homeId));
        if (CollectionUtils.isEmpty(integer) && integer.size() < 1) {
            return 0;
        }
        if (CollectionUtils.isNotEmpty(integer) && integer.size() > 0) {
            String accessToken = getEzTokenByUser(organizationCode);
            if (StringUtils.isNotEmpty(accessToken)) {
                String[] split = accessToken.split("&");
                accessToken = split[0];
                for (EzvizTokenDO item : integer) {
                    SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
                    clientHttpRequestFactory.setReadTimeout(1000);
                    restTemplate.setRequestFactory(clientHttpRequestFactory);
                    String url = "https://open.ys7.com/api/lapp/ram/account/get?accessToken=" + accessToken + "&" + "accountId=" + item.getEzvizId();
                    ResponseEntity<EzResult> forEntity = restTemplate.postForEntity(url, null, EzResult.class);
                    if (forEntity.getStatusCode().value() == 200) {
                        Object data = forEntity.getBody().getData();
                        Map<String, Object> stringObjectMap = (Map<String, Object>) data;
                        Object policy = stringObjectMap.get("policy");
                        if (policy != null) {
                            throw new ZyServerException(ErrorType.Service_Fail.getCode(), "请先删除家庭中的萤石摄像头");
                        }
                    } else {
                        throw new ZyServerException(ErrorType.Service_Fail.getCode(), "萤石服务器访问错误请稍后访问");
                    }
                    return 0;
                }
            }
        }
        return null;
    }


    public String getEzTokenByUser(String orgCode) {
        Gson gson = new Gson();
        EzviewMessageBean persons = null;
        Object str = redisTemplate.opsForValue().get("ezviz." + orgCode);
        if (str == null) {
            try {
                EzViewDO ezViewDo = thirdDataMapper.selectEzView(orgCode);
                EzviewPost sendPostMessage = new EzviewPost();
                String jsonMessage = sendPostMessage.sendPost(
                        "https://open.ys7.com/api/lapp/token/get", "appKey=" + ezViewDo.getDataKey()
                                + "&appSecret=" + ezViewDo.getSecret());
                if (jsonMessage != null) {
                    persons = JSONObject.parseObject(jsonMessage, EzviewMessageBean.class);
                    persons = gson.fromJson(jsonMessage, EzviewMessageBean.class);
                }
            } catch (Exception e) {
                log.info("萤石主账号token异常 -> [getEzTokenByUser] -> [{}]", e.getCause());
            }
            String ezTokenMessage = persons.getData().getAccessToken() + "&" + persons.getData().getExpireTime();
            redisTemplate.opsForValue().set("ezviz." + orgCode, ezTokenMessage, 3, TimeUnit.DAYS);
            return ezTokenMessage;
        }
        return str.toString();
    }

    public EzvizTokenRepDTO saveOrUpdateChildIdAndRepChildMessage(EzvizTokenDO et) {
        EzvizTokenDO one = getOne(Wrappers.<EzvizTokenDO>lambdaQuery()
                .eq(EzvizTokenDO::getHomeId, et.getHomeId()));
        et.setId(one != null ? one.getId() : null);
        boolean b = saveOrUpdate(et);
        if (!b) {
            throw new ZyServerException(ErrorType.Service_Fail.getCode(), "萤石TOKEN处理失败！");
        }
        EzvizTokenDO byId = getById(et.getId());
        EzvizTokenRepDTO ezvizTokenRepDTO = new EzvizTokenRepDTO().ezvizTokenDoToEzvizTokenRepDto(byId);
        return ezvizTokenRepDTO;
    }
}
